/*
* a simple jQuery dropdown menu plugin
* oohacker, Jun 26th, 2012.
* mail: oohacker@qq.com
*=======================================
* compatibility:
* *jquery 1.4.3+
* *ie6.0+, ff, opera, safira
*
* enjoy it! :)
*/

(function($) {
	var submenus = [];
	var gid = 0;

	var createMenu = function(node, lvl, mid, target) {
		gid += 1;
		var submenu = $("<div></div>").attr("id", "ddmenu_"+gid);
		for(var i=0; i<=lvl; ++i) submenu.addClass("ddmenu_lv"+i);
		
		var set = $(node).children("li");
		var midx = 0;
		$.each(set, function(index, el) {
			var lnk = $(el).children("a").clone();
			var smid = gid+1;
			lnk.bind("mouseenter", function() {
				$(".ddmenu_lv" + (lvl+1)).slideUp("fast");
				if (ul.size() > 0) {
					var mobj = $("#ddmenu_"+smid);
					var pos = submenu.position();
					pos.top += submenu.outerHeight();
					mobj.css(pos);
					mobj.slideDown("fast");
				}
			}).appendTo(submenu);
			
			var ul = $("ul:first", $(el));
			if (ul.size() > 0) createMenu(ul, lvl+1, midx, target);
			midx++;
		});
		$("a", submenu).prev().after("<span class='ddmenu_sp'>|</span>");
		$(target).append(submenu);
	};
	
	$.fn.jqDDmenu = function(target) {
		var temp = $("<div></div>");
		var ulNode = $(this).is("ul") ? this : $("ul:first", this);
		createMenu(ulNode, 0, 0, temp);

		$(target).empty().append(temp.children());

		var inArea = false;
		$(".ddmenu_lv0").bind("mouseleave", function() {
			inArea = false;
			setTimeout(function(){if(!inArea)$(".ddmenu_lv1").slideUp("normal");}, 2000);
		});
		
		$(".ddmenu_lv0").bind("mouseenter", function() {
			inArea = true;
		});
		
		$(this).is("ul") ? $(this).detach() : $("ul", this).detach();
		$(".ddmenu_lv1").hide();
	};
})(jQuery);